<template>
  <div class="user-page page-view">
    <!-- 面包屑导航 -->
    <div class="breadcrumb">
      <div class="list">
        <div class="home-icon">
          <i class="iconfont icon-home"></i>
        </div>
        <div class="item">
          <router-link to="/">
            <span class="text">首页</span>
          </router-link>
        </div>
        <div class="seperate">
          <i class="iconfont icon-arrow-right-thin"></i>
        </div>
        <div class="item">
          <router-link to="/">
            <span class="text">用户管理</span>
          </router-link>
        </div>
        <div class="seperate">
          <i class="iconfont icon-arrow-right-thin"></i>
        </div>
        <div class="item">
          <span class="text">{{ isEdit ? '编辑用户' : '添加用户' }}</span>
        </div>
      </div>
      <h1 class="page-title">{{ isEdit ? '编辑用户' : '添加用户' }}</h1>
    </div>

    <!-- 表单区域 -->
    <div class="form-wrapper">
      <form @submit.prevent="handleSubmit">
        <div class="form-section">
          <h3>基本信息</h3>
          <div class="form-grid">
            <div class="form-group">
              <label>用户名 <span class="required">*</span></label>
              <input
                v-model="formData.username"
                type="text"
                placeholder="请输入用户名"
                required
              />
            </div>

            <div class="form-group">
              <label>手机号 <span class="required">*</span></label>
              <input
                v-model="formData.phone"
                type="tel"
                placeholder="请输入手机号"
                required
              />
            </div>

            <div class="form-group">
              <label>用户类型 <span class="required">*</span></label>
              <select v-model="formData.user_type" required>
                <option value="1">管理员</option>
                <option value="2">普通用户</option>
              </select>
            </div>

            <div class="form-group" v-if="!isEdit">
              <label>密码 <span class="required">*</span></label>
              <input
                v-model="formData.password"
                type="password"
                placeholder="请输入密码"
                required
              />
            </div>

            <div class="form-group" v-if="!isEdit">
              <label>确认密码 <span class="required">*</span></label>
              <input
                v-model="formData.confirm_password"
                type="password"
                placeholder="请再次输入密码"
                required
              />
            </div>

            <div class="form-group" v-if="isEdit">
              <label>重置密码</label>
              <input
                v-model="resetPassword"
                type="password"
                placeholder="不修改请留空"
              />
            </div>

            <div class="form-group">
              <label>状态 <span class="required">*</span></label>
              <select v-model="formData.status" required>
                <option value="1">启用</option>
                <option value="0">禁用</option>
              </select>
            </div>

            <div class="form-group" v-if="isEdit">
              <label>创建时间</label>
              <input
                :value="formatTimestamp(formData.created_at)"
                type="text"
                disabled
              />
            </div>

            <div class="form-group" v-if="isEdit">
              <label>更新时间</label>
              <input
                :value="formatTimestamp(formData.updated_at)"
                type="text"
                disabled
              />
            </div>
          </div>
        </div>

        <!-- 操作按钮 -->
        <div class="form-actions">
          <button type="button" class="v-button" @click="handleCancel">取消</button>
          <button type="submit" class="v-button primary" :disabled="loading">
            {{ loading ? '提交中...' : (isEdit ? '更新' : '添加') }}
          </button>
        </div>
      </form>
    </div>
  </div>
</template>

<script setup>
import { ref, computed, onMounted } from "vue";
import { useRoute, useRouter } from "vue-router";
import { get, post } from "@/utils/request";
import { formatDate } from "@/utils/date";
import { vToast } from "@/plugins/vToast";

const route = useRoute();
const router = useRouter();

const isEdit = computed(() => route.name === 'UserEdit');
const loading = ref(false);
const resetPassword = ref('');

// 表单数据
const formData = ref({
  id: null,
  username: "",
  phone: "",
  user_type: "2", // 默认普通用户
  password: "",
  confirm_password: "",
  status: "1", // 默认启用
  created_at: null,
  updated_at: null,
});

// 格式化时间戳
const formatTimestamp = (timestamp) => {
  if (!timestamp) return "-";
  return formatDate(new Date(timestamp * 1000));
};

// 获取用户详情
const fetchUserDetail = async () => {
  if (!isEdit.value) return;

  loading.value = true;
  try {
    const res = await get(`/user/detail?id=${route.params.id}`);
    
    if (res.code === 200) {
      const user = res.data;
      formData.value = {
        id: user.id,
        username: user.username,
        phone: user.mobile, // 后端返回的是mobile字段
        user_type: user.permission, // 后端返回的是permission字段
        status: user.status.toString(), // 保持不变
        created_at: user.create_time, // 后端返回的是create_time字段
        password: '', // 编辑时不显示密码
        confirm_password: ''
      };
    } else {
      vToast.error(res.msg || "获取用户详情失败");
      router.push("/");
    }
  } catch (error) {
    vToast.error("获取用户详情失败");
    console.error(error);
    router.push("/");
  } finally {
    loading.value = false;
  }
};

// 提交表单
const handleSubmit = async () => {
  // 表单验证
  if (!formData.value.username || !formData.value.phone) {
    vToast.error("请填写必填字段");
    return;
  }

  // 验证手机号格式 - 支持标准手机号和sub_11_数字_数字格式
  const phoneRegex = /^(1[3-9]\d{9}|sub_11_\d+_\d+)$/;
  if (!phoneRegex.test(formData.value.phone)) {
    vToast.error("请输入正确的手机号格式");
    return;
  }

  // 新用户或重置密码时验证密码
  if ((!isEdit.value && (!formData.value.password || !formData.value.confirm_password)) ||
      (isEdit.value && resetPassword.value && formData.value.password !== formData.value.confirm_password)) {
    vToast.error("请填写密码并确保两次输入一致");
    return;
  }

  // 验证密码一致性
  if (!isEdit.value && formData.value.password !== formData.value.confirm_password) {
    vToast.error("两次输入的密码不一致");
    return;
  }

  loading.value = true;
  try {
    const submitData = {
      username: formData.value.username,
      phone: formData.value.phone,
      user_type: parseInt(formData.value.user_type),
      status: parseInt(formData.value.status),
    };

    if (isEdit.value) {
      submitData.id = formData.value.id;
      if (resetPassword.value) {
        submitData.password = resetPassword.value;
      }
      const res = await post("/user/update", submitData);
      
      if (res.code === 200) {
        vToast.success("用户更新成功");
        router.push("/");
      } else {
        vToast.error(res.msg || "更新失败");
      }
    } else {
      submitData.password = formData.value.password;
      const res = await post("/user/add", submitData);
      
      if (res.code === 200) {
        vToast.success("用户添加成功");
        router.push("/");
      } else {
        vToast.error(res.msg || "添加失败");
      }
    }
  } catch (error) {
    vToast.error(isEdit.value ? "更新失败" : "添加失败");
    console.error(error);
  } finally {
    loading.value = false;
  }
};

// 取消操作
const handleCancel = () => {
  router.push("/");
};

// 初始化数据
onMounted(() => {
  fetchUserDetail();
});
</script>

<style scoped lang="less">
.user-page {
  .breadcrumb {
    margin-bottom: 20px;
    
    .list {
      display: flex;
      align-items: center;
      font-size: 14px;
      
      .home-icon {
        color: #999;
      }
      
      .item {
        margin-right: 8px;
        
        .text {
          color: #333;
          
          &:hover {
            color: var(--v-theme);
          }
        }
      }
      
      .seperate {
        margin-right: 8px;
        color: #999;
      }
    }
    
    .page-title {
      margin-top: 10px;
      font-size: 24px;
      font-weight: 500;
      color: #333;
    }
  }

  .form-wrapper {
    background: var(--v-card-bg);
    border-radius: var(--v-card-radius);
    padding: 24px;
    margin-bottom: 20px;
  }

  .form-section {
    margin-bottom: 24px;

    h3 {
      font-size: 16px;
      font-weight: 500;
      color: var(--v-text);
      margin-bottom: 16px;
      padding-bottom: 12px;
      border-bottom: 1px solid var(--v-border-color);
    }
  }

  .form-grid {
    display: grid;
    grid-template-columns: repeat(auto-fit, minmax(300px, 1fr));
    gap: 20px;
  }

  .form-group {
    display: flex;
    flex-direction: column;
    gap: 8px;

    label {
      font-size: 14px;
      color: var(--v-text);
      font-weight: 500;

      .required {
        color: var(--v-danger);
      }
    }

    input,
    select,
    textarea {
      padding: 10px 12px;
      border: 1px solid var(--v-border-color);
      border-radius: var(--v-card-radius);
      background: var(--v-background-pure);
      color: var(--v-text);
      font-size: 14px;
      outline: none;
      transition: border-color 0.3s;

      &:focus {
        border-color: var(--v-theme);
      }

      &[disabled] {
        background: var(--v-background);
        color: var(--v-text-light);
        cursor: not-allowed;
      }

      &::placeholder {
        color: var(--v-text-light);
      }
    }

    textarea {
      resize: vertical;
      min-height: 100px;
    }
  }

  .form-actions {
    display: flex;
    gap: 12px;
    justify-content: flex-end;
    padding-top: 20px;
    border-top: 1px solid var(--v-border-color);

    .v-button {
      min-width: 80px;
      height: 40px;
      padding: 0 16px;
      border-radius: var(--v-card-radius);
      font-size: 14px;
      font-weight: 500;
      cursor: pointer;
      transition: all 0.3s;
      border: 1px solid var(--v-border-color);
      background: var(--v-background-pure);
      color: var(--v-text);

      &:hover:not(:disabled) {
        border-color: var(--v-theme);
        color: var(--v-theme);
      }

      &:disabled {
        opacity: 0.5;
        cursor: not-allowed;
      }

      &.primary {
        background: var(--v-theme);
        border-color: var(--v-theme);
        color: white;

        &:hover:not(:disabled) {
          background: var(--v-theme-dark);
          border-color: var(--v-theme-dark);
        }
      }
    }
  }
}
</style>